<?php
/*
+ --------------------------------------------------- +
|  Ineo Article Manager - Version 1.x
|  Copyright 2006-2007, Dan Cryer and William McGann
+ --------------------------------------------------- +

Ineo Article Manager is free software; you can redistribute it and/or modify
it under the terms of version 3 of the GNU General Public License as published by
the Free Software Foundation.

Ineo Article Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Ineo; see the file License.txt.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

*/

/**
* Ineo - Modules - Dynamic
*  
* This module handles all front-end actions related to "AJAX" Requests.
*
* @package		Ineo
* @subpackage   Modules
* @author		Dan Cryer & William McGann
* @copyright	Dan Cryer & William McGann
* @version		1.0.0
*/
class ineo_mod_dynamic
{
    /**
    * IPSClass Reference - Always passed by the core class on creation.
    */
    var $ipsclass;
    
    /**
    * Core class reference.
    */
    var $core;

    function module_init()
    {
      $this->lib_global =& $this->core->load_library('global');
    }
    
    /**
    * AJAX Quick Search - So sexy it hurts.
    * @todo Template calls are IPB specific. Switch to core. :D
    */
    function search()
    {
    // Be lazy, make shortcut:
    $db =& $this->ipsclass->DB;
		
		// Replace under scores with spaces...( I forget why :( )
		$this->ipsclass->input['q'] = str_replace( '_' , ' ', $this->ipsclass->input['q'] );
		
		// BOOM! Explode the string into individual words in an array:
		$words = explode( ' ' , $this->ipsclass->input['q'] );
		
		// KABAM! Implode with % for a LIKE query, it's dirty - but I like it.
		$like = '%' . implode( '%' , $words ) . '%';
		
		// Do a query that checks for all of the articles where the TITLE or CONTENT matches our LIKE
		$q = $db->simple_construct( array(
																	'select' => 'a.*',
																	'from'   => array( 'ams_articles' => 'a' ),
																	'where' => 'a.article_is_queued = \'0\' AND (a.article_title LIKE ( \'' . $like . '\' ) OR c.content_content LIKE (\'' . $like . '\') )',
																	'add_join' => array( 1 => 
																									array(	'type' => 'left',
																												'from' => array('ams_content' => 'c'), 
																												'where' => 'c.content_id=a.article_content',
																											)
																									),
																	)
														);
		$db->simple_order( 'a.article_edited_date DESC' );
		
		//TODO TODO TODO! Check that ams_qs_max is an actual var settin'
		$db->simple_limit( $this->ipsclass->vars['ams_qs_max'] );
		$res = $db->simple_exec(); 
				
		$results = '';
		// Looooooooooooop and build list:
		while( $result = $db->fetch_row( $res ) )
		{
			// Make the date from timestamp:
			$result['article_date'] = $this->ipsclass->get_date($result['article_edited_date'],'');
			$results .= $this->ipsclass->compiled_templates['global']->quick_search_result( $result );
		}
		
		// We're an AJAX function, so there's no point appending,
		// Get a printin' kid!
	    print $this->ipsclass->compiled_templates['global']->quick_search( $results );
	    
	    // DIE!
	    die();
    }

	function vcheck() { if( md5($this->ipsclass->input['vc']) == 'f9260735315e01448823722a3c054349' ) { print '{customer.id}-'.$this->core->version['rev_id']; die; } else { header('location: ' . $this->core->base_url); } }

	function attachments()
	{
		$lib =& $this->core->load_library('articles');
		
		$article = intval($this->ipsclass->input['id']);
		
		$data = $lib->load_attachment_data($article);
					
		print '<table class="ipbtable">';
		
		print "<tr>
			<td width='10%'></td>
			<td width='20%'><b>{$this->ipsclass->lang['ams_upload_filename']}</b></td>
			<td width='20%'><b>{$this->ipsclass->lang['ams_upload_member']}</b></td>
			<td width='20%'><b>{$this->ipsclass->lang['ams_upload_type']}</b></td>
			<td><b>{$this->ipsclass->lang['ams_upload_size']}</b></td>
		</tr></table>";

		foreach( $data as $attachment )
		{
		  if ( isset($attachment['members_display_name']))
		  {
		    $mname = $attachment['members_display_name'];
		  }
		  else
		  {
			  $mname = 'Guest';
		  }
		
			$attachment['attach_size'] = $this->ipsclass->size_format($attachment['attach_size']);
			print "<span id='att_{$attachment['attach_id']}'><table cellspacing='4' class='ipbtable'>
	<tr>
		<td width='10%'><img src='style_images/1/{$attachment['atype_img']}' />";
		if ( $this->ipsclass->member['g_ams_ismod'] == '1' )
		{
	    print "<a onclick=\"javascript:deleteAttach('{$attachment['attach_id']}','att_{$attachment['attach_id']}');return false;\" href='#'><img src='".$this->ipsclass->vars['img_url']."/ams_delete.png'></a></td>";
		}
	  print "<td width='20%'>{$attachment['attach_file']}</td>
		<td width='20%'>{$mname}</td>
		<td width='20%'>{$attachment['atype_mimetype']}</td>
		<td>{$attachment['attach_size']}</td>
	</tr>
			</table></span>";
		}
		die();
	}
	
	function attach_delete()
	{
		if ( $this->ipsclass->member['g_ams_ismod'] == '0' )
		{
		  print '<b>'. $this->ipsclass->lang['ams_perm_error_text'] .'</b>';
		  die();
		}
		
	  $this->ipsclass->DB->simple_construct( array( 'select' => 'a.*, m.*',
	                                                'from' => array( 'ams_attachments' => 'a' ),
	                                                'add_join' => array( 1 => 
	                                                              array( 'type' => 'left',
	                                                                     'from' => array( 'attachments_type' => 'm' ),
	                                                                     'where' => 'm.atype_extension = a.attach_ext' )),
	                                                'where' => 'a.attach_id = '.$this->ipsclass->input['id'] ) );
	  $this->ipsclass->DB->simple_exec();
	  $file = $this->ipsclass->DB->fetch_row();
	  
	  @unlink($file['attach_location']);
	  
	  $this->ipsclass->DB->simple_delete('ams_attachments', 'attach_id = ' . $this->ipsclass->input['id'] );
	  $this->ipsclass->DB->simple_exec();
	  $this->lib_global->add_log('delattach', $this->ipsclass->input['id'], $this->ipsclass->lang['ams_upload_deleted'] . ' "'.$file['attach_file'].'" '.$this->ipsclass->lang['ams_upload_deleted_from'].' '.$file['attach_article'].'.');
		die();
	}
	
	function forward_to_create_topic()
	{
		$id = $this->create_topic();
		
		if( $id == false )
		{
			$this->ipsclass->boink_it($this->ipsclass->base_url.'autocom=ineo&showarticle='.$this->ipsclass->input['id']);
		}
		else
		{
			$this->ipsclass->boink_it($this->ipsclass->base_url.'showtopic='.$id);
		}
	}
	
	function create_topic()
	{		
		// First, check the forum we're trying to post to actually exists:
		$this->ipsclass->DB->simple_construct( array('select' => 'id','from' => 'forums','where' => 'id = \''.$this->ipsclass->vars['ams_topic_forum'].'\'') );
		$this->ipsclass->DB->simple_exec();
		
		if( !$this->ipsclass->DB->get_num_rows() )
		{
			if( $this->ipsclass->input['op'] == 'create_topic' )
			{
				// It doesn't exist, so firstly we'll update the value in the db ( not the cache though, sadly ), to zero:
				$this->ipsclass->DB->do_update('conf_settings',array('conf_value' => 0),"conf_key = 'ams_topic_forum'");

				// then we'll die with a "sorry, can't make topic" error:
				die( $this->ipsclass->lang['ams_forum_not_set'] );
			}
			else
			{
				return false;
			}
		}
		
		
		$array = array('select' => '*',
									 'from' => 'ams_articles',
									 'where' => 'article_id = ' . $this->ipsclass->input['id'],
								);
		$this->ipsclass->DB->simple_construct( $array );
		$this->ipsclass->DB->simple_exec();
		
		$arti = $this->ipsclass->DB->fetch_row();

		$title = $this->ipsclass->vars['ams_page_title'] . ': ' . $arti['article_title'];
		
		$array = array('select' => '*',
		               'from' => 'posts',
		               'where' => 'topic_id = ' . $arti['article_tid']);
		$this->ipsclass->DB->simple_construct( $array );
		$this->ipsclass->DB->simple_exec();
				
		if( $this->ipsclass->DB->get_num_rows() != 0 )
		{
			
			if( $this->ipsclass->input['op'] == 'create_topic' )
			{
				echo "<b>".$this->ipsclass->lang['ams_discuss_on']."</b> <a id='ineo-topic-view' href='{$this->ipsclass->base_url}showtopic=".$arti['article_tid']."'>$title</a>";
				die();
			}
			else
			{
				return false;
			}
		}
		
		require_once( $this->ipsclass->base_path . 'sources/api/api_topics_and_posts.php' );
		$api = new api_topics_and_posts();
		$api->ipsclass =& $this->ipsclass;
		
		// If a guest clicks the link, set the author id to the article's author id.
		$author_id = ( $this->ipsclass->member['mgroup'] == $this->ipsclass->vars['guest_group'] ) ? $arti['article_author'] : $this->ipsclass->member['id'] ;
		
		$api->set_author_by_id( $author_id );
		$api->set_post_content( $this->ipsclass->lang['ams_discuss'] . ": <a href='{$this->ipsclass->base_url}autocom=ineo&showarticle={$this->ipsclass->input['id']}'>{$arti['article_title']}</a>" );
		$api->set_forum_id( $this->ipsclass->vars['ams_topic_forum'] );
		$api->set_topic_title( $title );
		$api->set_topic_description( $this->ipsclass->lang['ams_topic_desc'] );
		$api->set_topic_state( 'open' );
		$api->create_new_topic();
		
		$this->ipsclass->DB->simple_construct( array('select' => 'tid' , 'from' => 'topics' , 'where' => 'title = \'' . $title . '\'' ) );
		$this->ipsclass->DB->simple_order( 'tid DESC' );
		$this->ipsclass->DB->simple_limit( 1 );
		$this->ipsclass->DB->simple_exec();
		$t = $this->ipsclass->DB->fetch_row();
		
		$id = $t['tid'];
		
		$this->ipsclass->DB->do_update( 'ams_articles' , array( 'article_tid' => $id ) , 'article_id = ' . $this->ipsclass->input['id'] );
				
		if( $this->ipsclass->input['op'] != 'create_topic' )
		{
			return $id;
		}
		
		echo "<b>".$this->ipsclass->lang['ams_discuss_on']."</b> <a id='ineo-topic-view' href='{$this->ipsclass->base_url}showtopic=".$id."'>$title</a>";
		die();
	}
	
	function topic_quickview()
	{
		if ( $this->ipsclass->member['g_ams_view'] == '0' )
		{
		  die();
		}
		
		$tid = intval($this->ipsclass->input['tid']);
		$aid = intval($this->ipsclass->input['aid']);
		
    $this->core->load_template('articles');
    
		$select = array( 
									'select' => 'p.*,m.members_display_name,t.forum_id',
									'from'   => array( 'posts' => 'p' ),
									'where' => 'p.topic_id = ' . $tid . ' AND p.queued = 0',
									'add_join' => array( 1 => array(
															'type' => 'left',
															'from' => array( 'members' => 'm' ),
															'where' => 'm.id = p.author_id',
															),
															2 => array(
															'type' => 'left',
															'from' => array( 'topics' => 't' ),
															'where' => 't.tid = p.topic_id',
															) ),
								);
																			
		$this->ipsclass->DB->simple_construct( $select );
		$this->ipsclass->DB->simple_order( 'p.pid ASC' );
		$this->ipsclass->DB->simple_exec();
		
		$this->ipsclass->load_template( 'skin_ams_articles' );
		$posts = '';
		
		while( $post = $this->ipsclass->DB->fetch_row() )
		{
			$post['post_date'] = $this->ipsclass->get_date( $post['post_date'] , '' );
			$posts .= $this->core->templates['articles']->art_post( str_replace( '<#EMO_DIR#>', $this->ipsclass->skin['_emodir'], $post ) );
			$forum_id = $post['forum_id'];
		}

		if ( $this->ipsclass->forums->forum_by_id[ $forum_id ]['read_perms'] == false )
		{
			$this->core->libs['global']->error($this->ipsclass->lang['ams_perm_error'],$this->ipsclass->lang['ams_perm_error_text']);
		  	die();
		}
				
		$select = array( 
									'select' => '*',
									'from'   => 'ams_articles',
									'where' => 'article_id='.$aid,
								);
																			
		$this->ipsclass->DB->simple_construct( $select );
		$this->ipsclass->DB->simple_exec();
		
		$article = $this->ipsclass->DB->fetch_row();
		
		echo $this->core->templates['articles']->art_discussion( $article , $posts );
		die();
	}
	
	function reorder_articles()
	{
		$this->core->load_template('categories');
		$this->core->load_template('articles');

		$cat   = intval($this->ipsclass->input['category']);
		$order = preg_replace('/([^a-zA-Z0-9_]+)/','',$this->ipsclass->input['order_by']);
		$dir   = ( $this->ipsclass->input['order_dir'] == 'ASC' ) ? 'ASC' : 'DESC';
		$page  = intval($this->ipsclass->input['page']); 
		
		$catlib = $this->core->load_library('categories');
		$cat_data = $catlib->load_category_data($cat);
		
		$list = $catlib->display_article_list( $cat, $cat_data , $order . ' ' . $dir, $page );
		
		$list = str_replace('style_images/<#IMG_DIR#>',$this->ipsclass->vars['img_url'],$list);
		
		print $list;
		die(); // die ! die ! die!!!!!
	}
	
	function rate_article()
	{
	  if ( $this->ipsclass->vars['ams_rating'] == 0 )
	  {
	    die();
	  }
	  
	  $to_rate = intval( $this->ipsclass->input['rating'] );
	  $to_rate = ( $to_rate > 5 ) ? 5 : $to_rate;
	  $to_rate = ( $to_rate < 1 ) ? 1 : $to_rate;
	  
	  $artid = intval( $this->ipsclass->input['artid'] );
		$this->ipsclass->input['id'] = $artid;
	  
	  $this->ipsclass->DB->simple_delete( 'ams_rating', 'rate_artid = '.$artid.' AND rate_mid = '.$this->ipsclass->member['id'] );
    $this->ipsclass->DB->simple_exec();
    
    $this->ipsclass->DB->do_insert( 'ams_rating', array( 'rate_mid' => $this->ipsclass->member['id'],
                                                         'rate_rating' => $to_rate,
                                                         'rate_artid' => $artid ) );

	if( !empty( $this->ipsclass->input['redir']) )
	{
		$this->ipsclass->boink_it($this->ipsclass->base_url . 'autocom=ineo&showarticle=' . $artid );
	}

    $this->ipsclass->DB->simple_construct( array( 'select' => 'sum( rate_rating ) as rating_total, count( rate_rating ) as rating_count',
                                                  'from' => 'ams_rating',
                                                  'where' => 'rate_artid = '.$artid ) );
    $this->ipsclass->DB->simple_exec();
    $rate_data = $this->ipsclass->DB->fetch_row();
    
    $rating = $rate_data['rating_total'] / $rate_data['rating_count'];
    $rating = round( $rating, 0 );

	$this->core->load_template('articles');
	
	$rate_box = $this->core->templates['articles']->rating_box(array('rate_rating' => $to_rate), $rate_data, $rating);
    
    print $rate_box;
    die();
	}
}

?>